﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessModel;
using Controller;

namespace ManageStore.Forms
{
    public partial class FrmSale : Form, INotifyPropertyChanged
    {
        public FrmSale()
        {
            InitializeComponent();
            SaleProductCtr = new SaleProductCtr();
        }
      
        private void FrmSale_Load(object sender, EventArgs e)
        {
            BindingAmount(txtTotal, "TotalAmount");
            BindingAmount(txtTotalCustomer, "TotalCustomer");
            BindingAmount(txtTotalReturn, "TotalReturn");

            saleOrderBindingSource.DataSource = _SaleProductCtr.SaleOrder;
            //dgvProduct.AutoGenerateColumns = false;
            //SaleProductCtr.SaleOrder.SaleOrderDetails.Add(new SaleOrderDetail());
            //dgvProduct.DataSource = SaleProductCtr.SaleOrder.SaleOrderDetails;
        }

        #region Properties
        private int _TotalAmount;
        public int TotalAmount
        {
            get { return _TotalAmount; }
            set { _TotalAmount = value; PropertyChanged(this, new PropertyChangedEventArgs("TotalAmount")); }
        }
        private int _TotalCustomer;
        public int TotalCustomer
        {
            get { return _TotalCustomer; }
            set { _TotalCustomer = value; TotalReturn = value - TotalAmount; }
        }
        private int _TotalReturn;
        public int TotalReturn
        {
            get { return _TotalReturn; }
            set { _TotalReturn = value; PropertyChanged(this, new PropertyChangedEventArgs("TotalReturn")); }
        }
        #endregion Properties
        private void BindingAmount(TextBox pTextBox, string pProName)
        {
            Binding oBinding = new Binding("Text", this, pProName);
            oBinding.FormattingEnabled = true;
            oBinding.DataSourceUpdateMode = DataSourceUpdateMode.OnValidation;
            oBinding.FormatString = "#,#";
            pTextBox.DataBindings.Add(oBinding);
        }

        //SaleProductCtr
        private SaleProductCtr _SaleProductCtr;
        public SaleProductCtr SaleProductCtr
        {
            get { return _SaleProductCtr; }
            set { _SaleProductCtr = value; }
        }

        private void CreateNew()
        {
            _SaleProductCtr.SaleOrder = new SaleOrder();
            saleOrderBindingSource.DataSource = _SaleProductCtr.SaleOrder;
            TotalAmount = TotalCustomer = TotalReturn = 0;
            //txtTotal.Text = txtTotalCustomer.Text = txtTotalReturn.Text = "0";
        }

        private void ProcessTotal()
        {
            int iTotal = 0;
            foreach (SaleOrderDetail item in SaleProductCtr.SaleOrder.SaleOrderDetails)
            {
                iTotal += item.Total;
            }
            TotalAmount = iTotal;
            //txtTotal.Text = iTotal.ToString();
        }

        private void dgvProduct_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            DataGridViewComboBoxCell cell = dgvProduct.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewComboBoxCell;
            if (cell != null && cell.DataSource == null || dgvProduct.Columns[e.ColumnIndex].Name == "UnitId")
            //if (cell != null || dgvProduct.Columns[e.ColumnIndex].Name == "UnitId")
            {
                switch (dgvProduct.Columns[e.ColumnIndex].Name)
                {
                    case "ProductCode":
                        if (cell.DataSource != null)
                            break;
                        cell.DisplayMember = "Code";
                        cell.ValueMember = "Id";
                        cell.DataSource = SaleProductCtr.CbbProduct;
                        break;
                    case "ProductName":
                        if (cell.DataSource != null)
                            break;
                        cell.DisplayMember = "Name";
                        cell.ValueMember = "Id";
                        cell.DataSource = SaleProductCtr.CbbProduct;
                        break;
                    case "UnitId":
                        cell.DisplayMember = "UnitName";
                        cell.ValueMember = "UnitId";
                        SaleProductCtr.CbbUnitChange = SaleProductCtr.GetUnitChangeByProductId(_SaleProductCtr.SaleOrder.SaleOrderDetails[e.RowIndex].ProductId1, DateTime.Now.Date).ToResult<List<UnitChange>>();
                        cell.DataSource = SaleProductCtr.CbbUnitChange.Where(p => p.Level.HasValue).ToList();
                        break;
                }
            }
        }

        private void dgvProduct_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            switch (dgvProduct.Columns[e.ColumnIndex].Name)
            {
                case "ProductCode":
                    DataGridViewComboBoxCell cbbName = dgvProduct.Rows[e.RowIndex].Cells["ProductName"] as DataGridViewComboBoxCell;
                    if (cbbName.DataSource != null)
                        break;
                    cbbName.DisplayMember = "Name";
                    cbbName.ValueMember = "Id";
                    cbbName.DataSource = SaleProductCtr.CbbProduct;
                    break;
                case "ProductName":
                    DataGridViewComboBoxCell cbbCode = dgvProduct.Rows[e.RowIndex].Cells["ProductCode"] as DataGridViewComboBoxCell;
                    if (cbbCode.DataSource != null)
                        break;
                    cbbCode.DisplayMember = "Code";
                    cbbCode.ValueMember = "Id";
                    cbbCode.DataSource = SaleProductCtr.CbbProduct;
                    break;
                case "UnitId":
                    if (dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value != null)
                    {
                        UnitChange unit = SaleProductCtr.CbbUnitChange.Where(p => p.UnitId == int.Parse(dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value.ToString())).FirstOrDefault();
                        if (unit != null)
                            dgvProduct.Rows[e.RowIndex].Cells["SalePriceUnit"].Value = unit.SalePriceUnit;
                    }
                    break;
                case "Quantity":
                    if (dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value != null)
                    {
                        int iQuantity = 0;
                        int.TryParse(dgvProduct.Rows[e.RowIndex].Cells["Quantity"].Value.ToString(), out iQuantity);
                        bool isWoleSale = false;
                        UnitChange unit = SaleProductCtr.CbbUnitChange.Where(p => !p.Level.HasValue && p.UnitId == int.Parse(dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value.ToString())).FirstOrDefault();
                        if (unit != null)
                        {
                            if (iQuantity >= unit.Quantity)
                            {
                                dgvProduct.Rows[e.RowIndex].Cells["SalePriceUnit"].Value = unit.SalePriceUnit;
                                isWoleSale = true;
                            }
                        }
                        if (!isWoleSale)
                        {
                            unit = SaleProductCtr.CbbUnitChange.Where(p => p.UnitId == int.Parse(dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value.ToString())).FirstOrDefault();
                            dgvProduct.Rows[e.RowIndex].Cells["SalePriceUnit"].Value = unit.SalePriceUnit;
                        }
                    }
                    break;
                case "SalePriceUnit":
                    break;
            }
        }

        private void dgvProduct_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is ComboBox)
            {
                (e.Control as ComboBox).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                (e.Control as ComboBox).AutoCompleteSource = AutoCompleteSource.ListItems;
                (e.Control as ComboBox).DropDownStyle = ComboBoxStyle.DropDown;
                (e.Control as ComboBox).SelectedIndex = 0;
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            CreateNew();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            _SaleProductCtr.SaveSaleOrder(_SaleProductCtr.SaleOrder);
            CreateNew();
        }

        private void dgvProduct_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void dgvProduct_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex == dgvProduct.Rows.Count - 1)
                return;
            string sError = string.Empty;
            int iQuantity = 0;
            // ProductName.
            if (dgvProduct.Rows[e.RowIndex].Cells["ProductCode"].Value == null || dgvProduct.Rows[e.RowIndex].Cells["ProductName"].Value == null)
            {
                sError += "Chưa chọn hàng hóa.\r\n";
            }
            else
            {
                if (SaleProductCtr.SaleOrder.SaleOrderDetails[e.RowIndex].ProductId.HasValue)
                {
                    if (SaleProductCtr.SaleOrder.SaleOrderDetails.Where(p => p.ProductId == SaleProductCtr.SaleOrder.SaleOrderDetails[e.RowIndex].ProductId).Count() > 1)
                        sError += "Hàng này đã được chọn rồi.\r\n";
                    else
                    {
                        Product oProduct = SaleProductCtr.CbbProduct.Where(p => p.Id == SaleProductCtr.SaleOrder.SaleOrderDetails[e.RowIndex].ProductId1).FirstOrDefault();
                        if (oProduct != null)
                            iQuantity = oProduct.Quantity.Value;
                        else
                            sError += "Chọn lại hàng hoá.\r\n";
                    }
                }
            }
            // UnitId.
            if (dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value == null)
            {
                sError += "Chưa chọn đơn vị tính.\r\n";
            }
            // Quantity.
            if (dgvProduct.Rows[e.RowIndex].Cells["Quantity"].Value == null || int.Parse(dgvProduct.Rows[e.RowIndex].Cells["Quantity"].Value.ToString()) < 1)
            {
                sError += "Số lượng phải là số nguyên dương lớn 0.\r\n";
            }
            else
            {
                if (dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value != null)
                {
                    int iUnitId = int.Parse(dgvProduct.Rows[e.RowIndex].Cells["UnitId"].Value.ToString());
                    UnitChange oUnitChange = null;
                    if (SaleProductCtr.SaleOrder.SaleOrderDetails[e.RowIndex].ProductId.HasValue)
                    {
                        oUnitChange = SaleProductCtr.CbbUnitChange.Where(p => p.UnitId == iUnitId).FirstOrDefault();
                    }
                    int iInputQuantity = int.Parse(dgvProduct.Rows[e.RowIndex].Cells["Quantity"].Value.ToString());
                    if (oUnitChange != null && oUnitChange.Quantity.HasValue)
                    {
                        iInputQuantity *= oUnitChange.Quantity.Value;
                    }
                    if (iInputQuantity > iQuantity)
                        sError += "Số lượng còn trong kho là : " + iQuantity + ".\r\n";
                }
            }
            // SalePriceUnit.
            if (dgvProduct.Rows[e.RowIndex].Cells["SalePriceUnit"].Value == null || int.Parse(dgvProduct.Rows[e.RowIndex].Cells["SalePriceUnit"].Value.ToString()) < 1)
            {
                sError += "Đơn giá bán phải là số nguyên dương lớn 0.\r\n";
            }
            if (!string.IsNullOrEmpty(sError))
            {
                MessageBox.Show(sError, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            else
            {
            }
        }

        private void dgvProduct_RowValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < dgvProduct.Rows.Count - 1)
            {
                dgvProduct.Rows[e.RowIndex].Cells["Total"].Value =
                    int.Parse(dgvProduct.Rows[e.RowIndex].Cells["Quantity"].Value.ToString()) * int.Parse(dgvProduct.Rows[e.RowIndex].Cells["SalePriceUnit"].Value.ToString());
                ProcessTotal();
            }
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

        private void dgvProduct_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show("" + dgvProduct.Rows[0].Cells["ProductCode"].Value);
        }

        private void dgvProduct_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //MessageBox.Show("" + dgvProduct.Rows[0].Cells["ProductCode"].Value);
        }

        private void FrmSale_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
